//
//  LocationCityViewController.m
//  House
//
//  Created by 张垚 on 16/6/24.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "LocationCityViewController.h"
#import "BaseTitleNavigationBar.h"
#import "NetRequest.h"
#import "MBProgressHUD.h"
#import "LocationManager.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "MBProgressHUD.h"

@interface LocationCityViewController ()<UITableViewDataSource, UITableViewDelegate>
//顶部视图
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
//城市列表
@property (nonatomic, strong) NSMutableArray *cityArr;
//tableview
@property (nonatomic, strong) UITableView *tableView;
//进度条
@property (nonatomic, strong) MBProgressHUD *hud;
//定位按钮
@property (nonatomic, strong) UIButton *locationButton;
//开通城市列表
@property (nonatomic, strong) NSMutableArray *openCityArr;

@end

@implementation LocationCityViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //开通城市 -- 后台接口
    _openCityArr = @[@"上海市", @"北京市", @"广州市", @"哈尔滨"].mutableCopy;
    //顶部视图
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"热门城市"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
     [_myBar.leftView addGestureRecognizer:tap];
    //定位
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_locationButton setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
    [_myBar addSubview:_locationButton];
    [_locationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_myBar.mas_right).offset(-10);
        make.bottom.equalTo(_myBar.mas_bottom).offset(-5);
        make.size.mas_equalTo(CGSizeMake(25, 30));
    }];
    _locationButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [_locationButton addTarget:self action:@selector(location:) forControlEvents:UIControlEventTouchUpInside];
    //tableview
    [self initTableView];
    //进度
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    //    _hud.dimBackground = YES;
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    //城市列表数据
    [self initLoadData];

    // Do any additional setup after loading the view.
}

//block传值
- (void)passCityBlock:(cityNameBlock)cityNameBlock {
    self.cityBlock = cityNameBlock;
}
//定位
- (void)location:(UIButton *)button {
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    //    _hud.dimBackground = YES;
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    LocationManager *location = [LocationManager manager];
    [location requestLocationWithBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        _hud.label.text = @"定位成功";
        [_hud hideAnimated:YES afterDelay:1];
        if ([_openCityArr containsObject:regeocode.city]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"系统定位到您在%@,需要切换到%@吗？", regeocode.city, regeocode.city] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    NSString *cityStr = [regeocode.city substringToIndex:regeocode.city.length - 1];
                    self.cityBlock(cityStr);
                    [self back];
                }];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [alertController addAction:sureAction];
                [self presentViewController:alertController animated:YES completion:nil];
            });
        }else {
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"当前定位城市为%@,该城市暂未开通", regeocode.city] preferredStyle:UIAlertControllerStyleAlert];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:YES completion:nil];
            });
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];
    
}

//城市列表数据
- (void)initLoadData {
    [NetRequest getInformationWithGetMethodWithUrl:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_address" success:^(NSURLSessionDataTask *task, id responseObject) {
        _hud.label.text = @"获取成功";
        [_hud hideAnimated:YES afterDelay:1];
        _cityArr = responseObject;
        NSLog(@"%@", responseObject);
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];

}
//tableview
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [UIView new];
    
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dic = _cityArr[section];
    if ([dic[@"arr"] isKindOfClass:[NSNull class]]) {
        return 0;
    }else {
        NSArray *arr = dic[@"arr"];
        return arr.count;
    }
   
}
//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cityArr.count;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *str = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
       
    }else {
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView *)cell.contentView.subviews.lastObject removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    NSDictionary *dic = _cityArr[indexPath.section];
    if ([dic[@"arr"] isKindOfClass:[NSNull class]]) {
        
    }else {
        NSArray *arr = dic[@"arr"];
        NSDictionary *dic = arr[indexPath.row];
        cell.textLabel.text = dic[@"areaname"];
        cell.tag = [dic[@"id"] integerValue];
    }
   
    return cell;
}
//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([_openCityArr containsObject:cell.textLabel.text]) {
        NSDictionary *dic = _cityArr[indexPath.section];
        NSArray *arr = dic[@"arr"];
        NSDictionary *areaDic = arr[indexPath.row];
        if ([areaDic[@"arr"] isKindOfClass:[NSNull class]]) {
            NSLog(@"没有区域");
        }else {
            YTKKeyValueStore *areaStore = [[YTKKeyValueStore alloc] initDBWithName:dataBaseName];
            [areaStore createTableWithName:tableName];
            [areaStore putObject:areaDic[@"arr"] withId:areaDic[@"id"] intoTable:tableName];
            [[NSUserDefaults standardUserDefaults] setObject:areaDic[@"id"] forKey:cityID];
            [[NSUserDefaults standardUserDefaults] synchronize];
            self.cityBlock(cell.textLabel.text);
            [self back];
        }
            }else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"该城市暂未开通服务" preferredStyle:UIAlertControllerStyleAlert];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
     NSDictionary *dic = _cityArr[section];
    return dic[@"areaname"];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
